package com.hjm.project.finance.agentDeductions.controller;

import com.hjm.common.utils.Utils;
import com.hjm.common.utils.poi.ExcelUtil;
import com.hjm.common.utils.yh.PoiUtil;
import com.hjm.framework.aspectj.lang.annotation.Log;
import com.hjm.framework.aspectj.lang.enums.BusinessType;
import com.hjm.framework.web.controller.BaseController;
import com.hjm.framework.web.domain.AjaxResult;
import com.hjm.framework.web.page.TableDataInfo;
import com.hjm.project.agentInfo.agentInfo.domain.AgentInfo;
import com.hjm.project.agentInfo.agentInfo.service.IAgentInfoService;
import com.hjm.project.finance.agentDeductions.domain.AgentDeductions;
import com.hjm.project.finance.agentDeductions.service.IAgentDeductionsService;
import com.hjm.project.finance.agentDeductionsDetails.domain.AgentDeductionsDetails;
import com.hjm.project.finance.agentDeductionsDetails.service.IAgentDeductionsDetailsService;
import com.hjm.project.finance.record.domain.AgentDeductionsRecord;
import com.hjm.project.finance.record.service.IAgentDeductionsRecordService;
import com.hjm.project.team.teamYlInfo.domain.TeamYlInfo;
import com.hjm.project.team.teamYlInfo.service.ITeamYlInfoService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 代理商扣款规则Controller
 * 
 * @author maker-platform
 * @date 2022-10-21
 */
@Controller
@RequestMapping("/finance/agentDeductions")
public class AgentDeductionsController extends BaseController {
    private String prefix = "finance/agentDeductions";

    @Resource
    private IAgentDeductionsService agentDeductionsService;
    @Resource
    private IAgentDeductionsDetailsService iAgentDeductionsDetailsService;
    @Resource
    private IAgentInfoService agentInfoService;
    @Resource
    private IAgentDeductionsRecordService iAgentDeductionsRecordService;
    @Resource
    private ITeamYlInfoService iTeamYlInfoService;

    @RequiresPermissions("finance:agentDeductions:view")
    @GetMapping()
    public String agentDeductions() {
        return prefix + "/agentDeductions";
    }

    /**
     * 查询代理商扣款规则列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AgentDeductions agentDeductions) {
        startPage();
        List<AgentDeductions> list = agentDeductionsService.selectAgentDeductionsList(agentDeductions);
        return getDataTable(list);
    }

    /**
     * 导出代理商扣款规则列表
     */
    @RequiresPermissions("finance:agentDeductions:export")
    @Log(title = "代理商扣款规则", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AgentDeductions agentDeductions) {
        List<AgentDeductions> list = agentDeductionsService.selectAgentDeductionsList(agentDeductions);
        ExcelUtil<AgentDeductions> util = new ExcelUtil<AgentDeductions>(AgentDeductions.class);
        return util.exportExcel(list, "agentDeductions");
    }

    /**
     * 新增代理商扣款规则
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存代理商扣款规则
     */
    @RequiresPermissions("finance:agentDeductions:add")
    @Log(title = "代理商扣款规则", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AgentDeductions agentDeductions, MultipartFile file, @RequestParam Map map) {
        int result = 0;
        boolean isError = true;
        String message = "";
        try {
            if (agentDeductions.getSn().equals("") && agentDeductions.getDeductionType() == 2) {
                if (file == null) {
                    isError = false;
                    message = "请上传终端Excel文件";
                    return AjaxResult.warn("请上传终端Excel文件");
                }
                if (file.getSize() == 0) {
                    isError = false;
                    message = "请上传正确的终端Excel文件";
                    return AjaxResult.warn("请上传正确的终端Excel文件");
                }
                File files = File.createTempFile("prefix", "_" + file.getOriginalFilename());
                file.transferTo(files);
                Map<String, Map<String, Object>> lines = PoiUtil.readExcelContent(files.getPath());

                String newSn = "";
                for (Map ss : lines.values()) {
                    String sn = ss.get("key0").toString();
                    newSn += sn + ",";
                }
                String substring = newSn.substring(0, newSn.length() - 1);
                agentDeductions.setSn(substring);
            }

            agentDeductions.setAddMan(this.getSysUser().getObjNo());
            agentDeductions.setAddDate(Utils.formateDate(0));
            agentDeductions.setAuditStatus(3);
            if (agentDeductions.getDeductionType() == 1) { //扣款类型为机具扣款时
                agentDeductions.setPosNumber(0);
                agentDeductions.setSn("");
            } else {
                agentDeductions.setDeductionMoney(agentDeductions.getDeductionMoney().multiply(BigDecimal.valueOf(Long.valueOf(agentDeductions.getPosNumber().toString()))));
            }
            //获取‘100000000’账户
            AgentInfo agentInfo = new AgentInfo();
            agentInfo.setAgentNum("100000000");
            List<AgentInfo> agentInfos = agentInfoService.selectTopAgentInfo(agentInfo);
            //默认收款账户
            agentDeductions.setProAgentName(agentInfos.get(0).getAgentName());
            agentDeductions.setProAgentNum(agentInfos.get(0).getAgentNum());
            //剩余扣款金额取总扣款金额
            agentDeductions.setDeductionMoneyD(agentDeductions.getDeductionMoney());
            result = agentDeductionsService.insertAgentDeductions(agentDeductions);
            //判断是否有终端
            if (!agentDeductions.getSn().isEmpty()) {//保存到代理商扣款明细表
                String[] sns = agentDeductions.getSn().split(",");
                for (String s : sns) {
                    AgentDeductionsDetails agentDeductionsDetails = new AgentDeductionsDetails();
                    agentDeductionsDetails.setPosType(agentDeductions.getPosType().toString());
                    agentDeductionsDetails.setSn(s);
                    agentDeductionsDetails.setDeductionType(2);
                    agentDeductionsDetails.setRatio(agentDeductions.getRatio());
                    agentDeductionsDetails.setDeductionMoney(agentDeductions.getDeductionMoney().divide(BigDecimal.valueOf(Long.valueOf(agentDeductions.getPosNumber().toString()))));
                    agentDeductionsDetails.setIsDeduction(0);
                    agentDeductionsDetails.setDeductionDate(Utils.formateDate(0));
                    agentDeductionsDetails.setAd_id(agentDeductions.getId().toString());
                    result = iAgentDeductionsDetailsService.insertAgentDeductionsDetails(agentDeductionsDetails);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return toAjax(result);
    }

    /**
     * 修改代理商扣款规则
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        AgentDeductions agentDeductions = agentDeductionsService.selectAgentDeductionsById(id);
        //sn
        String sn = "";
        //扣款明细对象
        AgentDeductionsDetails agentDeductionsDetails = new AgentDeductionsDetails();
        agentDeductionsDetails.setAd_id(id.toString());
        //获取扣款明细
        List<AgentDeductionsDetails> agentDeductionsDetailsList = iAgentDeductionsDetailsService.selectAgentDeductionsDetailsList(agentDeductionsDetails);
        for (AgentDeductionsDetails agentDeductionsDetails1 :agentDeductionsDetailsList){
            sn = sn + (sn.equals("")? agentDeductionsDetails1.getSn() : "," + agentDeductionsDetails1.getSn());
        }
        agentDeductions.setSn(sn);
        mmap.put("agentDeductions", agentDeductions);
        return prefix + "/edit";
    }

    /**
     * 修改保存代理商扣款规则
     */
    @RequiresPermissions("finance:agentDeductions:edit")
    @Log(title = "代理商扣款规则", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AgentDeductions agentDeductions) {
        //判断状态是否为已上传或审核成功-不允许修改
        AgentDeductions agentDeductions1 = agentDeductionsService.selectAgentDeductionsById(agentDeductions.getId());
        if(agentDeductions1 != null && agentDeductions1.getAuditStatus() != null){
            if(agentDeductions1.getAuditStatus() == 1 || agentDeductions1.getAuditStatus() == 2){
                return AjaxResult.warn("改条数据已上传或审核成功，请刷新重试！");
            }
        }
        if(agentDeductions.getDeductionType() == 1){ //扣款类型为机具扣款时
            agentDeductions.setPosNumber(0);
            agentDeductions.setSn("");
        }else{
            agentDeductions.setDeductionMoney(agentDeductions.getDeductionMoney().multiply(BigDecimal.valueOf(Long.valueOf(agentDeductions.getPosNumber().toString()))));
        }
        //剩余扣款金额取总扣款金额
        agentDeductions.setDeductionMoneyD(agentDeductions.getDeductionMoney());
        int result = agentDeductionsService.updateAgentDeductions(agentDeductions);
        //删除明细表内对应数据
        iAgentDeductionsDetailsService.deleteAgentDeductionsDetailsByAdId(agentDeductions.getId());
        //判断是否有终端
        if(!agentDeductions.getSn().isEmpty()){//保存到代理商扣款明细表
            String[] sns = agentDeductions.getSn().split(",");
            for(String s :sns){
                AgentDeductionsDetails agentDeductionsDetails = new AgentDeductionsDetails();
                agentDeductionsDetails.setPosType(agentDeductions.getPosType().toString());
                agentDeductionsDetails.setSn(s);
                agentDeductionsDetails.setDeductionType(2);
                agentDeductionsDetails.setRatio(agentDeductions.getRatio());
                agentDeductionsDetails.setDeductionMoney(agentDeductions.getDeductionMoney().divide(BigDecimal.valueOf(Long.valueOf(agentDeductions.getPosNumber().toString()))));
                agentDeductionsDetails.setIsDeduction(0);
                agentDeductionsDetails.setDeductionDate(Utils.formateDate(0));
                agentDeductionsDetails.setAd_id(agentDeductions.getId().toString());
                result = iAgentDeductionsDetailsService.insertAgentDeductionsDetails(agentDeductionsDetails);   //保存明细
            }
        }
        return toAjax(result);
    }

    /**
     * 删除代理商扣款规则
     */
    @RequiresPermissions("finance:agentDeductions:remove")
    @Log(title = "代理商扣款规则", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        //判断状态是否为已上传或审核成功-不允许删除
        /*AgentDeductions agentDeductions1 = agentDeductionsService.selectAgentDeductionsById(Integer.parseInt(ids));
        if(agentDeductions1 != null && agentDeductions1.getAuditStatus() != null){
            if(agentDeductions1.getAuditStatus() == 1 || agentDeductions1.getAuditStatus() == 2){
                return AjaxResult.warn("已经上传或审核成功，不允许删除，请刷新后重试！");
            }
        }*/
        int result = iAgentDeductionsDetailsService.deleteAgentDeductionsDetailsByAdId(Integer.parseInt(ids));
        result = agentDeductionsService.deleteAgentDeductionsByIds(ids);
        return toAjax(result);
    }

    /**
     * 上传
     * @param ids
     * @return
     */
    @PostMapping("/upadd")
    @ResponseBody
    public AjaxResult upadd(String ids) {
        //判断状态是否为已上传或审核成功-不允许修改
        AgentDeductions agentDeductions1 = agentDeductionsService.selectAgentDeductionsById(Integer.parseInt(ids));
        if(agentDeductions1 != null && agentDeductions1.getAuditStatus() != null){
            if(agentDeductions1.getAuditStatus() == 1 || agentDeductions1.getAuditStatus() == 2){
                return AjaxResult.warn("已经上传，请刷新后重试！");
            }
        }
        return toAjax(agentDeductionsService.upaddAgentDeductionsByIds(ids));

    }

    /**
     * 审核界面
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/audits")
    public String audits(@RequestParam Integer id, ModelMap mmap){
        AgentDeductions agentDeductions = agentDeductionsService.selectAgentDeductionsById(id);
        //sn
        String sn = "";
        //扣款明细对象
        AgentDeductionsDetails agentDeductionsDetails = new AgentDeductionsDetails();
        agentDeductionsDetails.setAd_id(id.toString());
        //获取扣款明细
        List<AgentDeductionsDetails> agentDeductionsDetailsList = iAgentDeductionsDetailsService.selectAgentDeductionsDetailsList(agentDeductionsDetails);
        for (AgentDeductionsDetails agentDeductionsDetails1 :agentDeductionsDetailsList){
            sn = sn + (sn.equals("")? agentDeductionsDetails1.getSn() : "," + agentDeductionsDetails1.getSn());
        }
        agentDeductions.setSn(sn);
        mmap.put("agentDeductions", agentDeductions);
        return prefix + "/audit";
    }

    /**
     * 审核代理商扣款规则
     * @param agentDeductions
     * @return
     */
    @PostMapping("/saveAudit")
    @ResponseBody
    public AjaxResult saveAudit(AgentDeductions agentDeductions) {
        return toAjax(agentDeductionsService.auditAgentDeductions(agentDeductions));
    }

    /**
     * 配置收款账户界面
     */
    @GetMapping("/exitAccount")
    public String exitAccount(@RequestParam Integer id ,ModelMap mmp){
        AgentDeductions agentDeductions = agentDeductionsService.selectAgentDeductionsById(id);
        mmp.addAttribute("id",id);
        mmp.addAttribute("proAgentNum",agentDeductions.getProAgentNum());
        mmp.addAttribute("proAgentName",agentDeductions.getProAgentName());
        mmp.addAttribute("proIsYl",agentDeductions.getProIsYl());
        mmp.addAttribute("proYlName",agentDeductions.getProYlName());
        mmp.addAttribute("proYlId",agentDeductions.getProYlId());
        return prefix + "/exitAccount";
    }

    /**
     * 配置收款账户
     */
    @RequestMapping("/saveAccount")
    @ResponseBody
    @Log(title = "配置收款账户", businessType = BusinessType.UPDATE)
    public AjaxResult saveAccount(AgentDeductions agentDeductions)
    {
        if(agentDeductions.getProIsYl() == 1){
            agentDeductions.setProAgentNum(agentDeductions.getProAgentNum1());
            agentDeductions.setProAgentName("");
        }else{
            agentDeductions.setProYlId("0");
        }
        AgentDeductions agentDeductions1 = agentDeductionsService.selectAgentDeductionsById(agentDeductions.getId());

        AgentDeductionsRecord agentDeductionsRecord = new AgentDeductionsRecord();
        agentDeductionsRecord.setAdId(agentDeductions.getId()); //扣款序号
        agentDeductionsRecord.setAgentBefore(agentDeductions1.getProAgentNum() != null ? agentDeductions1.getProAgentNum() : "");    //更改之前
        agentDeductionsRecord.setAgentLater(agentDeductions.getProAgentNum() != null ? agentDeductions.getProAgentNum() : "");  //更改之后
        agentDeductionsRecord.setAddMan(this.getSysUser().getLoginName());  //  变更人
        agentDeductionsRecord.setAddDate(Utils.formateDate(2)); //变更时间
        agentDeductionsRecord.setProYlIdBefore(agentDeductions1.getProYlId() != null ? agentDeductions1.getProYlId() : "");  //团长编号变更前
        agentDeductionsRecord.setProYlIdLater(agentDeductions.getProYlId() != null ? agentDeductions.getProYlId() : "");    //团长编号变更后
        iAgentDeductionsRecordService.insertAgentDeductionsRecord(agentDeductionsRecord);

        return toAjax(agentDeductionsService.updateAgentDeductions(agentDeductions));
    }

    /**
     * 选择服务商申请列表顶级
     */
    @GetMapping("/selectAgent")
    public String selectAgent(){
        return prefix + "/selectAgent";
    }

    /**
     * 查询服务商申请列表顶级
     */
    @PostMapping("/selectAgentInfo")
    @ResponseBody
    public TableDataInfo selectAgentInfo(AgentInfo agentInfo)
    {
        startPage();
        List<AgentInfo> agentInfos = agentInfoService.selectTopAgentInfo(agentInfo);
        return getDataTable(agentInfos);
    }

    /**
     * 选择sn终端
     */
    @GetMapping("/selectPosInfo")
    public String selectPosInfo(@RequestParam String pos_type,String agent_num,String sns, ModelMap map)
    {
        map.put("pos_type",pos_type);
        map.put("agent_num",agent_num);
        map.put("sns",sns);
        return "terminal/terminal/selectPosInfo";
    }

    /**
     * 选择服务商
     * @return
     */
    @GetMapping("/selectAgentInfo2")
    public String selectAgentInfo(){
        return prefix+"/selectAgentInfo";
    }


    /**
     * 选择服务商申请列表顶级
     */
    @GetMapping("/selectYl")
    public String selectYl(String ylId, String ylName, ModelMap map){
        map.addAttribute("ylId",ylId);
        map.addAttribute("ylName",ylName);
        return prefix + "/selectYl";
    }

    /**
     * 查询服务商申请列表顶级
     */
    @PostMapping("/selectYlTeam")
    @ResponseBody
    public TableDataInfo selectYlTeam(TeamYlInfo teamYlInfo)
    {
        startPage();
        List<TeamYlInfo> teamYlInfos = iTeamYlInfoService.selectAllTeamYl(teamYlInfo);
        return getDataTable(teamYlInfos);
    }
}
